package com.nd.realm;

import com.nd.dao.UserMapper;
import com.nd.pojo.bean.Admin;
import com.nd.pojo.bean.AdminExample;
import com.nd.pojo.bean.User;
import com.nd.pojo.bean.UserExample;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

public class WxRealm extends AuthorizingRealm {

    @Autowired
    UserMapper userMapper;
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        MallToken token = (MallToken) authenticationToken;
        String username = token.getUsername();
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);
        //用户不存在，抛出空指针
//        if(users.size() == 0) return null;
        User user = users.get(0);
        //更新用户的最新登录时间
        user.setLastLoginTime(new Date());
        userMapper.updateByPrimaryKeySelective(user);
        //加盐
        ByteSource salt = ByteSource.Util.bytes(username);
        return new SimpleAuthenticationInfo(user,user.getPassword(),salt,this.getName());
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //todo 用户购物车授权
        return null;
    }

}
